import 'dart:async';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  //确保插件服务被初始化，以便于' availableCameras() ' 可以在' runApp() '之前调用
  // Ensure that plugin services are initialized so that `availableCameras()`
  // can be called before `runApp()`
  WidgetsFlutterBinding.ensureInitialized();

  //获取设备上可用的摄像机列表。
  // Obtain a list of the available cameras on the device.
  final cameras = await availableCameras();

  //从可用相机列表中获取一个特定的相机。
  // Get a specific camera from the list of available cameras.
  final firstCamera = cameras.first;

  runApp(
    MaterialApp(
      theme: ThemeData.light(),
      home: TakePictureScreen(
        //将适当的摄像机传递给TakePictureScreen部件。
        // Pass the appropriate camera to the TakePictureScreen widget.
        camera: firstCamera,
      ),
    ),
  );
}

//一种允许用户使用给定的相机拍照的屏幕。
// A screen that allows users to take a picture using a given camera.
class TakePictureScreen extends StatefulWidget {
  const TakePictureScreen({
    Key? key,
    required this.camera,
  }) : super(key: key);

  final CameraDescription camera;

  @override
  TakePictureScreenState createState() => TakePictureScreenState();
}

class TakePictureScreenState extends State<TakePictureScreen> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;

  @override
  void initState() {
    super.initState();
    //从相机显示当前输出， 创建一个CameraController
    // To display the current output from the Camera,
    // create a CameraController.
    _controller = CameraController(
      // Get a specific camera from the list of available cameras.从可用相机列表中获取一个特定的相机。
      widget.camera,
      // Define the resolution to use.定义要使用的分辨率。
      ResolutionPreset.medium,
    );
    //接下来，初始化控制器。这将返回Future。
    // Next, initialize the controller. This returns a Future.
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    // Dispose of the controller when the widget is disposed.
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Take a picture')),
      //控件的初始化之前，必须等待控制器初始化,相机预览。使用FutureBuilder显示加载微调轮，直到控制器已初始化。
      // You must wait until the controller is initialized before displaying the
      // camera preview. Use a FutureBuilder to display a loading spinner until the
      // controller has finished initializing.
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            // If the Future is complete, display the preview.如果Future已完成，则显示预览。
            return CameraPreview(_controller);
          } else {
            // Otherwise, display a loading indicator. 否则，显示加载指示灯
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
      //1.一个拍照按钮
      floatingActionButton: FloatingActionButton(
        // Provide an onPressed callback.
        onPressed: () async {
          // Take the Picture in a try / catch block. If anything goes wrong,catch the error.
          try {
            // Ensure that the camera is initialized.确保摄像机已初始化。
            await _initializeControllerFuture;

            // Attempt to take a picture and get the file `image` where it was saved.
            // 尝试拍摄一张照片，并获得文件' image '在那里它被保存
            final image = await _controller.takePicture();

            // If the picture was taken, display it on a new screen.
            await Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => DisplayPictureScreen(
                  //将自动生成的路径传递到显示图片窗口小部件。
                  // Pass the automatically generated path to
                  // the DisplayPictureScreen widget.
                  imagePath: image.path,
                ),
              ),
            );
          } catch (e) {
            // If an error occurs, log the error to the console. 如果发生错误，将错误记录到控制台。
            print(e);
          }
        },
        child: const Icon(Icons.camera_alt),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,//居中浮动

    );
  }
}

// A widget that displays the picture taken by the user.显示用户所拍照片的小部件。
class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;

  const DisplayPictureScreen({Key? key, required this.imagePath})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Display the Picture')),
      // The image is stored as a file on the device. Use the `Image.file`
      // constructor with the given path to display the image.
      body: Image.file(File(imagePath)),
    );
  }
}
